package com.hippo.core.aspect;

import com.hippo.core.annotation.Operation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * @ClassName OpenrationAspect
 * @Description TODO 操作日志
 * @Author tangxl
 * @create 2023-05-08 17:59
 **/
@Component
@Aspect
@Order(1)
@Slf4j
public class OpenrationAspect {
    /**
     * 定义切点，切点添加了@Operation注解的方法
     */
    @Pointcut("@annotation(com.hippo.core.annotation.Operation)")
    public void operationLog() {
    }

    /**
     * 环绕通知
     * 注：ProceedingJoinPoint只有在@Around注解中才能使用
     * @param joinPoint
     */
    @Around("operationLog()")
    public void doAfter(ProceedingJoinPoint joinPoint) {
        // 获取注解
        Operation operation = getOperation(joinPoint);
        // 获取注解属性值
        if(operation == null){
            return;
        }
        String module = operation.module();
        String type = operation.type();
        String desc = operation.desc();
        log.info("获取到的Operation注解属性值为：module={},type={},desc={}", module, type, desc);
    }

    //获取注解
    public Operation getOperation(ProceedingJoinPoint point) {
        Signature signature = point.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        if (method != null){
            return method.getAnnotation(Operation.class);
        }
        return null;
    }
}
